const scanImports = require('./scan.js');
const fs = require('fs-extra');
const path = require('path');
const { build } = require('esbuild');
const { normalizePath } = require('../utils.js');

async function createOptimizeDepsRun(config) {
  // deps: { 'vue': 'xxx/node_modules/vue/dist/vue.runtime.esm-bundler.js' }
  const deps = await scanImports(config);

  const { cacheDir } = config;
  // 创建 node_modules/.vite50/deps/_metadata.json 文件和相关内容
  const depsCacheDir = path.resolve(cacheDir, 'deps');
  const metadataPath = path.join(depsCacheDir, '_metadata.json');
  const metadata = {
    optimized: {},
  };
  for (const id in deps) {
    const entry = deps[id];
    // vue: { file: 'xxx', src: 'xxx' }
    metadata.optimized[id] = {
      file: normalizePath(path.resolve(depsCacheDir, id + '.js')), // xxx/node_modules/.vite50/deps/vue.js
      src: entry, // xxx/node_modules/vue/dist/vue.runtime.esm-bundler.js
    };

    // 写入依赖文件: 输出 deps 依赖项文件到 node_modules/.vite50/deps 目录里
    await build({
      absWorkingDir: process.cwd(),
      entryPoints: [entry],
      outfile: path.resolve(depsCacheDir, id + '.js'),
      bundle: true,
      write: true, // 写入到硬盘中
      format: 'esm',
    });
  }
  await fs.ensureDir(depsCacheDir); // 查看目录是否存在，如果不存在，则创建一个
  // 写入 node_modules/.vite50/deps/_metadata.json 文件内容
  await fs.writeFile(
    metadataPath,
    JSON.stringify(
      metadata,
      (key, value) => {
        if (key === 'file' || key === 'src') {
          // optimized里存的是绝对路径，此处写入硬盘的是相对于缓存目录的相对路径
          console.log(depsCacheDir, value);
          return normalizePath(path.relative(depsCacheDir, value));
        }
        return value;
      },
      2
    )
  );
  return { metadata };
}
exports.createOptimizeDepsRun = createOptimizeDepsRun;
